<?php

namespace App\Services;

use App\Models\CommodityActivitySkuStatistics;
use App\Models\CommodityActivityStatistics;
use App\Models\DailyReportStatistics;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;

class CacheLockKeyConst
{
    const FIRST_OR_CACTE_LOCK = 'FirstOrCache::';

    /**
     * 解决 DailyReportStatistics firstOrCreate 并发
     * @param CarbonInterface $date
     * @return Model|bool
     */
    public static function dailyReportStatistics(CarbonInterface $date)
    {
        return \Cache::lock(self::FIRST_OR_CACTE_LOCK . __FUNCTION__ . '_' . $date->format('Ymd'), 5)
            ->block(10, fn() => DailyReportStatistics::query()->firstOrCreate(['date' => $date->format('Y-m-d')]));
    }

    /**
     * 解决 CommodityActivityCultivationAwardStatistics firstOrCreate 并发
     * @param $commodityActivitySkuId
     * @param $commodityId
     * @param $commodityActivityId
     * @return Model|bool
     */
    public static function commodityActivitySkuStatistics($commodityActivitySkuId, $commodityId, $commodityActivityId)
    {
        return \Cache::lock(self::FIRST_OR_CACTE_LOCK . __FUNCTION__ . '_' . $commodityActivitySkuId, 5)
            ->block(10, fn() => CommodityActivitySkuStatistics::query()
                ->firstOrCreate(
                    ['commodity_activity_sku_id' => $commodityActivitySkuId],
                    ['commodity_id' => $commodityId, 'commodity_activity_id' => $commodityActivityId]
                ));
    }

    /**
     * 解决 CommodityActivityStatistics firstOrCreate 并发
     * @param $commodityId
     * @param $commodityActivityId
     * @return Model|bool
     */
    public static function commodityActivityStatistics($commodityId, $commodityActivityId)
    {
        return \Cache::lock(self::FIRST_OR_CACTE_LOCK . __FUNCTION__ . '_' . $commodityActivityId, 5)
            ->block(10, fn() => CommodityActivityStatistics::query()
                ->firstOrCreate(
                    ['commodity_activity_id' => $commodityActivityId],
                    ['commodity_id' => $commodityId]
                ));
    }
}
